import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    try {
      const user = await this.userService.validateUser(username, password);
      const { password: _, ...result } = user;
      return result;
    } catch (error) {
      return null;
    }
  }

  async login(user: any) {
    const payload = { username: user.nickname, sub: user.id };
    return {
      access_token: this.jwtService.sign(payload),
      user,
    };
  }

  async register(createUserDto: any) {
    const user = await this.userService.create(createUserDto);
    const { password: _, ...result } = user;
    return result;
  }
}
